Middleware是在request/response週期開始/結束修改request/response物件,這是express framework的feature。
以Logger功能為例,建立logger.middleware.ts
import { Injectable, NestMiddleware, MiddlewareFunction } from '@nestjs/common';
@Injectable()
export class LoggerMiddleware implements NestMiddleware { // 必須實作NestMiddleware介面
resolve(...args: any[]): MiddlewareFunction {
return (req, res, next) => { // 會接收request、response及next方法
console.log('Logger....');
next(); //告訴nest.js繼續下一個middleware,如果沒有,則交給request handler
};
}
}
Middleware是套用在Module Level,到app.module.ts新增middleware相關程式碼
修改app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './shared/middlewares/logger.middleware';
import { SharedModule } from './shared/shared.module';
import {cors} from 'cors'; //允許cors
@Module({
imports: [SharedModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule{
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware, cors) //指定要套用哪個Middleware,可以套用多個middleware,以逗點分隔
.forRoutes(AppController); // 指定哪些routes要套用,可以傳入Controller或是Controller陣列
}
}
用Postman發出request測試
其他設定
例如,POST不套用
修改app.module.ts如下:
...
configure(consumer: MiddlewareConsumer ) {
consumer
.apply(LoggerMiddleware, cors) // 要套用哪個Middleware,可以套用多個middleware,以逗點分隔
.exclude( // 列舉排除的routes
{ path: '/', method: RequestMethod.POST },
{ path: 'users', method: RequestMethod.GET}
)
.forRoutes(AppController); // 指定哪些routes要套用,可以傳入Controller或是Controller陣列
}
...